<?php

namespace app\api\controller;

use app\api\model\vipcard\Card as CardModel;
use app\api\model\vipcard\Order as OrderModel;
use app\api\service\Payment as PaymentService;
use app\common\enum\OrderType as OrderTypeEnum;
use app\api\service\vippay\PaySuccess;

/**
 * 用户购买储值卡管理
 * Class Recharge
 * @package app\api\controller
 */
class Vipcard extends Controller
{
    /**
     * 储值卡列表
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $money = $this->getUser()['money'];
        $shareholder = $this->getUser()['shareholder'];
	    // 储值卡列表
        $list = (new CardModel)->getList();
	    return $this->renderSuccess(compact('money','shareholder','list'));
       
    }

    /**
     * 储值卡详情
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        $param = $this->postData();
        $model = CardModel::detail($param['card_id'])?:[];
        return $this->renderSuccess($model);
    }



    /**
     * 确认充值
     * @param null $card_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function submit()
    {
        $param = $this->request->post();
        // 用户信息
        $userInfo = $this->getUser();
        // 生成充值订单
        $model = new OrderModel;
        if (!$model->createOrder($userInfo, $param['card_id'])) {
            return $this->renderError($model->getError() ?: '充值失败');
        }
        //获取订单详情
        $PaySuccess = new PaySuccess($model['order_no']);
        //订单支付金额为空
        if($model['pay_price']<=0){
            $status = $PaySuccess->freePaySuccess(20);
            $message = ['success' => '支付成功', 'error' => '订单已支付'];
            if($status){
                return $this->renderSuccess([],$message);
            }
        }

        // 构建微信支付
        $payment = PaymentService::wechat(
            $userInfo,
            $model['order_id'],
            $model['order_no'],
            $model['pay_price'],
            OrderTypeEnum::VIPPAY
        );
        // 充值状态提醒
        $message = ['success' => '充值成功', 'error' => '订单未支付'];
        return $this->renderSuccess(compact('payment', 'message'), $message);
    }



}
